// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {

	async kaidanlistAction(){
		let searchinfo = JSON.parse(this.post('searchinfo'))

		let where = {
			'o.departmentid': this.shop_userinfo.departmentid
		}
    
		if (searchinfo.times && (searchinfo.times[0] != null && searchinfo.times[1] != null)) {
			let begintime = Math.floor(new Date(searchinfo.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(searchinfo.times[1]).setHours(0,0,0,0)/1000) + 86400 // 当天加上一天
			where['o.addtime'] = {'>=': begintime, '<': endtime}
		}  

		if (searchinfo.ordertype != 0) where['o.ordertype'] = searchinfo.ordertype
		where['o.status'] = searchinfo.status == 0 ? ['!=', 0] : searchinfo.status
		if (searchinfo.search) where['g.name'] = ['like', '%' + searchinfo.search + '%']

		let list = await this.model('or_shop_order')
		.alias('o')
		.field('o.*, g.name')
		.join('`think_or_guest` g on g.id=o.guestid')
		.where(where)
		.page(searchinfo.currentPage, searchinfo.pageSize)
		.order('o.addtime desc')
		.countSelect()

		return this.json(list);
	}

	// 获取该订单的信息和业绩分配人员
	async getsubjectAction(){
		if (this.isGet) {
			let orderid = this.get('id');

			let orderinfo = await this.model().query('select * from `think_or_shop_orderinfo` where orderid='+orderid);
			let recemoney = await this.model().query('select xj.feat,u.name, u.id, z.name as zname,d.name as dname, 1 as type from `think_or_shop_yejixianjin` as xj left join `think_or_app_user` u on u.id=xj.userid left join `think_or_department` d on xj.bumenid=d.id left join `think_or_position` z on z.id=u.zhichengid where xj.orderid='+orderid);

			let consmoney = await this.model().query('select xh.feat,u.name, u.id, z.name as zname,d.name as dname, 2 as type from `think_or_shop_yejixiaohao` as xh left join `think_or_app_user` u on u.id=xh.userid left join `think_or_department` d on d.id=xh.bumenid left join `think_or_position` z on z.id=u.zhichengid where xh.orderid='+orderid);

			let redumoney = await this.model().query('select cd.feat,u.name, u.id, z.name as zname,d.name as dname, 3 as type from `think_or_shop_yejicardreduce` as cd left join `think_or_app_user` u on u.id=cd.userid left join `think_or_department` d on d.id=cd.bumenid left join `think_or_position` z on z.id=u.zhichengid where cd.orderid='+orderid);
			let data = {
				orderinfo : orderinfo,
				recemoney : recemoney,
				consmoney : consmoney,
				redumoney : redumoney,
			}
			return this.json(data);
		}
	}

	// 分配提成
	async fenpeitichengAction(){
		let data = JSON.parse(this.post('userinfo'));
		let orderid = this.post('orderid');
		let ordertype = this.post('ordertype');
		let addtime = Math.round(new Date().getTime()/1000);
		let orderinfo = await this.model('or_shop_order').where({id: orderid}).find()

		// 默认为流水单
		let isCanEditOrder = await this.isCanEditOrder(orderid, ordertype)
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}

		if (orderinfo.status == 2) {
			return this.fail('该订单已经分配业绩！')
		}

		// 确定发放月份
		let unix = new Date(orderinfo.addtime * 1000)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth
		let jiesuandate = nYear + '' + nMonth


		let basepay = [], fenpeitichengdata = []
		for (let i = 0, len = data.length; i < len; i++) {
			// 查询员工当月工资有没有发放
			let isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find()
			if (!think.isEmpty(isfafang)) {
				return this.fail('该订单时间段内有员工的工资已经发放！')
			}

			// 根据data去分配basetype
			if (data[i].xianjinticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 1,
					money : data[i].xianjinticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 1,
					yeji: data[i].xianjinyeji,
					money: data[i].xianjinticheng,
					tichengbi: 0
				})
			}
			if (data[i].kahaoticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 3,
					money : data[i].kahaoticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 3,
					yeji: data[i].kahaoyeji,
					money: data[i].kahaoticheng,
					tichengbi: 0
				})
			}
			if (data[i].shougongticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 2,
					money : data[i].shougongticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 2,
					yeji: 0,
					money: data[i].shougongticheng,
					tichengbi: 0
				})
			}
			if (data[i].qitaticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 4,
					money : data[i].qitaticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 4,
					yeji: 0,
					money: data[i].qitaticheng,
					tichengbi: 0
				})
			}
			data[i].id = ''
		}
		// console.log(data)
		let model = this.model('or_shop_userbasepay');
		await model.transaction(async () => {
			try {
				let res = fenpeitichengdata.length > 0 ? await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(fenpeitichengdata) : 1;

				let ot = ordertype == 1 ? 'KKD' : ordertype == 2 ? 'LSD' : 'CZD';

				let resdelticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: orderid, ordertype: ot}).delete();

				let resyejiticheng = data.length > 0 ? await this.model('or_shop_yejiticheng').db(model.db()).addMany(data) : 1;

				let baseInfo = basepay.length > 0 ? await model.addMany(basepay) : 1;

				let resorder = await this.model('or_shop_order').db(model.db()).where({id:orderid}).update({fenpei:1,status:2});

				if (resorder && res && baseInfo && resyejiticheng && resdelticheng !== false) {
					await model.commit();
					return this.success({info:'分配成功'});
				} else {
					await model.rollback();
					return this.fail('分配失败');
				}

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('分配失败');
			}
		})
	}

	async fanfenpeitichengAction() {
		let id = this.post('id')
		let shopid = this.shop_userinfo.departmentid;

		let orderinfo = await this.model('or_shop_order').where({id: id}).find();

		// 默认为流水单
		let isCanEditOrder = await this.isCanEditOrder(id, 'LSD')
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}

		let unix = new Date(orderinfo.addtime * 1000)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth
		let jiesuandate = nYear + '' + nMonth

		//要做哪些内容，删除分配的业绩，删除分配的工资，订单表状态改变
		let model = this.model('or_shop_userbasepay');
		await model.transaction(async () => {
			try {
				let youticheng = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).select();
				// 判断当前是否有员工工资发放
				if (!think.isEmpty(youticheng)) {
					let allYejiTicList = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id}).select();
					let isfafang = 1;
					for (var i = allYejiTicList.length - 1; i >= 0; i--) {
						isfafang = await this.model('or_shop_usergongzi').db(model.db()).where({shopid: shopid, userid: allYejiTicList[i].userid, jiesuandate: jiesuandate}).select()
						if (!think.isEmpty(isfafang)) {
							await model.rollback();
							return this.fail('该订单时间段内有员工的工资已经发放！')
						}
						allYejiTicList[i].xianjinticheng = 0;
						allYejiTicList[i].kahaoticheng = 0;
						allYejiTicList[i].shougongticheng = 0;
						allYejiTicList[i].qitaticheng = 0;
					}

					let resdelfen = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).delete();
					let delTicheng = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(allYejiTicList);
					let resdelub = await model.where({orderid: id, ordertype: ['IN', [1, 2, 3]]}).delete();
					let allotfinis = await this.model('or_shop_order').db(model.db()).where({id: id}).update({fenpei:0,status:1});
					
					if (allotfinis && resdelfen !== false && resdelub !== false && delTicheng) {
						await model.commit();
						return this.success({info:'操作成功'});
					} else {
						await model.rollback();
						return this.fail('操作失败');
					}
				}
				let allotfinis = await this.model('or_shop_order').db(model.db()).where({id: id}).update({fenpei:0,status:1});
				await model.commit();
				return this.success({info:'操作成功'});

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('操作失败');
			}
		})
	}

	async jianshaotichengAction(){

		let data = JSON.parse(this.post('userinfo'));

		let orderid = this.post('orderid');

		let ordertype = this.post('ordertype');

		let addtime = Math.round(new Date().getTime()/1000);

		let shopid = this.shop_userinfo.departmentid;

		let oInfo = await this.model('or_shop_backcardorder').where({id: orderid}).find()

		// 确定发放月份
		let unix = new Date(oInfo.addtime * 1000)

		let nYear = unix.getFullYear()

		let nMonth = unix.getMonth() + 1

		nMonth = nMonth < 10 ? '0' + nMonth : nMonth

		let jiesuandate = nYear + '' + nMonth

		for (let i = 0, len = data.length; i < len; i++) {
			// 查询员工当月工资有没有发放
			let isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find()

			if (!think.isEmpty(isfafang)) {
				return this.fail('该订单时间段内有员工的工资已经发放！')
			}

		}

		let model = this.model('or_shop_backcardorder');

		await model.transaction(async () => {

			try {

				if (data.length) {

					let basepay = [], fptcList = [], addTiCheng = [];

					for (var i = data.length - 1; i >= 0; i--) {
						basepay.push({
							userid : data[i].userid,
							category : 2,
							type : data[i].type,
							money : data[i].money,
							orderid : orderid,
							ordertype : ordertype,
							addtime : addtime,
							time: oInfo.addtime
						})

						fptcList.push({
							orderid: orderid,
							ordertype: ordertype,
							userid: data[i].userid,
							type: data[i].type,
							yeji: data[i].feat,
							tichengbi: data[i].percent,
							money: data[i].money,
							addtime: addtime
						})

						addTiCheng.push({
							shopid: shopid,
							orderid: orderid,
							ordertype: (ordertype==11?'TQD':'TKD'),
							addtype: data[i].type==1?0:1,
							xianjinyeji: data[i].type==1?data[i].feat:0,
							xianjinticheng: data[i].type==1?data[i].money:0,
							qitaticheng: data[i].type==1?0:data[i].money,
							userid: data[i].userid,
							bumenid: data[i].bumenid,
							xiaozuid: data[i].xiaozuid,
							addtime: addtime,
							guestid: oInfo.guestid
						})

					}

					let existFenPei = await this.model('or_shop_fenpeiticheng').db(model.db()).where({ordertype: ordertype, orderid: orderid}).select();
					if (!think.isEmpty(existFenPei)) {
						let delFenPei = await this.model('or_shop_fenpeiticheng').db(model.db()).where({ordertype: ordertype, orderid: orderid}).delete();
						if (!delFenPei) {
							await model.rollback();
							return this.fail('删除之前分配提成失败');
						}
					}

					let existUserBasePay = await this.model('or_shop_userbasepay').db(model.db()).where({ordertype: ordertype, orderid: orderid, category: 6}).select();
					if (!think.isEmpty(existUserBasePay)) {
						let delUserBasePay = await this.model('or_shop_userbasepay').db(model.db()).where({ordertype: ordertype, orderid: orderid, category: 6}).delete();
						if (!delUserBasePay) {
							await model.rollback();
							return this.fail('删除之前分配提成工资失败');
						}
					}

					let existTiCheng = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: orderid, ordertype: ['IN',['TKD', 'TQD']]}).select();
					if (!think.isEmpty(existTiCheng)) {
						let delTiCheng = await await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: orderid, ordertype: ['IN',['TKD', 'TQD']]}).delete();
						if (!delTiCheng) {
							await model.rollback();
							return this.fail('提成分配工资失败');
						}
					}

					// or_shop_fenpeiticheng
					let res = data.length ? await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(fptcList) : 1;

					// or_shop_userbasepay
					let baseInfo = basepay.length ? await this.model('or_shop_userbasepay').db(model.db()).addMany(basepay) : 1;

					// or_shop_yejiticheng
					let zeng = addTiCheng.length ? await this.model('or_shop_yejiticheng').db(model.db()).addMany(addTiCheng) : 1;

					if (!res && !baseInfo && !zeng) {
						await model.rollback();
						return this.fail('分配提成失败');
					}
				}

				let allotfinis = await model.db(model.db()).where({id:orderid}).update({status:2});

				if (allotfinis) {
					await model.commit();
					return this.success('分配成功');
				} else{
					await model.rollback();
					return this.fail('分配失败');
				}

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('分配失败');
			}
		})
	}

	// 重新分配扣除提成
	async againallotpercentAction(){
		let data = JSON.parse(this.post('userinfo'))

		let delus = JSON.parse(this.post('delus'))

		let orderid = this.post('orderid')

		let ordertype = this.post('ordertype')

		let shopid = this.shop_userinfo.departmentid;

		let addtime = Math.round(new Date().getTime()/1000)

		let oInfo = await this.model('or_shop_backcardorder').where({id: orderid}).find()

		// 确定发放月份
		let unix = new Date(oInfo.addtime * 1000)
		let jiesuandate = unix.getFullYear()+''+(unix.getMonth()<9?'0'+(unix.getMonth()+1):unix.getMonth()+1);

		let basepay = [], fenpeitichengdata = []

		for (var i = data.length - 1; i >= 0; i--) {
			// 查询员工当月工资有没有发放
			let isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find()

			if (!think.isEmpty(isfafang)) {
				return this.fail('该订单时间段内有员工的工资已经发放！')
			}
		}

		let model = this.model('or_shop_fenpeiticheng');

		await model.transaction(async ()=>{

			let gengFenpei = [], addFenpei = [], zengPay = [], zengTicheng = [];
			for (var i = data.length - 1; i >= 0; i--) {
				if (data[i].id) {
					gengFenpei.push({
						id: data[i].id,
						yeji: data[i].feat,
						tichengbi: data[i].percent,
						money: data[i].money
					})
				} else {
					addFenpei.push({
						orderid: orderid,
						ordertype: ordertype,
						userid: data[i].userid,
						type: data[i].type,
						yeji: data[i].feat,
						tichengbi: data[i].percent,
						money: data[i].money,
						addtime: addtime
					})
				}

				zengPay.push({
					userid: data[i].userid,
					category: 2,
					type: data[i].type,
					money: data[i].money,
					orderid: orderid,
					ordertype: ordertype,
					time: oInfo.addtime,
					addtime: addtime
				})
				
				zengTicheng.push({
					shopid: shopid,
					orderid: orderid,
					ordertype: (ordertype==10?'TKD':'TQD'),
					addtype: data[i].nodelete?0:1,
					xianjinyeji: data[i].nodelete?data[i].feat:0,
					xianjinticheng: data[i].nodelete?data[i].money:0,
					qitaticheng: data[i].nodelete?0:data[i].money,
					userid: data[i].userid,
					bumenid: data[i].bumenid,
					xiaozuid: data[i].xiaozuid,
					addtime: addtime,
					guestid: oInfo.guestid
				})
			}
			try {
				// 删除basepay表，yejiticheng表
				let paylength = await this.model('or_shop_userbasepay').db(model.db()).where({ordertype: ['IN', [10,11]], orderid: orderid}).select();

				if (!think.isEmpty(paylength)) {
					let delPay = await this.model('or_shop_userbasepay').db(model.db()).where({ordertype: ['IN', [10,11]], orderid: orderid}).delete();

					if (!delPay) {
						await model.rollback();
						return this.fail('分配失败');
					}
				}

				let addPay = zengPay.length?await this.model('or_shop_userbasepay').db(model.db()).addMany(zengPay):1;

				let ticlength = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: ['IN', ['TKD','TQD']], orderid: orderid}).select();

				if (!think.isEmpty(ticlength)) {
					let delTic = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: ['IN', ['TKD','TQD']], orderid: orderid}).delete();

					if (!delTic) {
						await model.rollback();
						return this.fail('分配失败');
					}
				}

				let addTic = zengTicheng.length?await this.model('or_shop_yejiticheng').db(model.db()).addMany(zengTicheng):1;

				let delFen = delus.length?await model.where({id: ['IN', delus]}).delete():1;

				let gengFp = gengFenpei.length?await model.updateMany(gengFenpei):1;

				let addFen = addFenpei.length?await model.addMany(addFenpei):1;

				if (addPay && addTic && delFen && gengFp && addFen) {
					await model.commit();
					return this.success('重新分配成功');
				} else {
					await model.rollback();
					return this.fail('重新分配失败');
				}

			} catch(e) {
				console.log(e)
				await model.rollback();
				return this.fail('重新分配失败');
			}

		})
	}

	// 重新分配
	async chongxinfenpeiAction () {
		let data = JSON.parse(this.post('userinfo'))

		let orderid = this.post('orderid')

		let ordertype = this.post('ordertype')

		let addtime = Math.round(new Date().getTime()/1000)

		let fenpeidata = [], paydata = []

		let orderform = 'or_shop_order'

		if (ordertype == 10 || ordertype == 11) {

			orderform = 'or_shop_backcardorder'

		}

		let isCanEditOrder = await this.isCanEditOrder(orderid, ordertype)
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}

		let orderinfo = await this.model(orderform).where({id: orderid}).find()

		// 确定发放月份
		let unix = new Date(orderinfo.addtime * 1000)
		let nYear = unix.getFullYear()
		let nMonth = unix.getMonth() + 1
		nMonth = nMonth < 10 ? '0' + nMonth : nMonth
		let jiesuandate = nYear + '' + nMonth

		let basepay = [], fenpeitichengdata = []
		for (var i = data.length - 1; i >= 0; i--) {
			// 查询员工当月工资有没有发放
			let isfafang = await this.model('or_shop_usergongzi').where({userid: data[i].userid, jiesuandate: jiesuandate}).find()

			if (!think.isEmpty(isfafang)) {
				return this.fail('该订单时间段内有员工的工资已经发放！')
			}

			// 根据data去分配basetype
			if (data[i].xianjinticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 1,
					money : data[i].xianjinticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 1,
					yeji: data[i].xianjinyeji,
					money: data[i].xianjinticheng,
					tichengbi: 0
				})
			}
			if (data[i].kahaoticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 3,
					money : data[i].kahaoticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 3,
					yeji: data[i].kahaoyeji,
					money: data[i].kahaoticheng,
					tichengbi: data[i].kahaotichengbi ? data[i].kahaotichengbi : 0
				})
			}
			if (data[i].shougongticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 2,
					money : data[i].shougongticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 2,
					yeji: 0,
					money: data[i].shougongticheng,
					tichengbi: 0
				})
			}
			if (data[i].qitaticheng > 0) {
				basepay.push({
					userid : data[i].userid,
					category : 2,
					type : 4,
					money : data[i].qitaticheng,
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					time: orderinfo.addtime
				})
				fenpeitichengdata.push({
					orderid : data[i].orderid,
					ordertype : ordertype,
					addtime : addtime,
					userid : data[i].userid,
					type : 4,
					yeji: 0,
					money: data[i].qitaticheng,
					tichengbi: 0
				})
			}
			data[i].id = ''
		}

		let model = this.model('or_shop_userbasepay')
		await model.transaction(async () => {
			try {
				// 先删除以前的
				let sulist = await this.model('or_shop_userbasepay')
				.db(model.db())
				.where({orderid: orderid, ordertype: ordertype})
				.select()

				for (var i = sulist.length - 1; i >= 0; i--) {
					let isfafang = await this.model('or_shop_usergongzi').db(model.db()).where({userid: sulist[i].userid, jiesuandate: jiesuandate}).find()
					if (!think.isEmpty(isfafang)) {
						await model.rollback();
						return this.fail('有员工工资已经审核不能再分配')
					}
				}

				let delfp = await this.model('or_shop_fenpeiticheng')
				.db(model.db())
				.where({orderid: orderid, ordertype: ordertype})
				.delete()

				let delub = await this.model('or_shop_userbasepay')
				.db(model.db())
				.where({orderid: orderid, ordertype: ordertype})
				.delete()

				let ot = ordertype == 1 ? 'KKD' : ordertype == 2 ? 'LSD' : 'CZD'

				let delyejiticheng = await this.model('or_shop_yejiticheng').where({orderid: orderid, ordertype: ot}).db(model.db()).delete()

				let resfp = fenpeitichengdata.length > 0 ? await this.model('or_shop_fenpeiticheng')
				.db(model.db())
				.addMany(fenpeitichengdata)
				:
				1
				let resub = basepay.length > 0 ? await model.addMany(basepay) : 1

				let resticheng = data.length > 0 ? await this.model('or_shop_yejiticheng').db(model.db()).addMany(data) : 1

				if (resticheng && resub && resfp && delub !== false && delfp !== false && delyejiticheng !== false) {
					await model.commit();
					return this.success({info:'分配成功'});
				} else {
					await model.rollback();
					return this.fail('分配失败');
				}
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('分配失败');
			}
		})
	}

	// 查看该订单所分配的信息
	async yifenpeiAction(){
		if (this.isGet) {
			let orderid = this.get('id');
			let fenpeiinfo = await this.model('or_shop_fenpeiticheng')
			.alias('fp')
			.field('fp.*, u.name')
			.join('think_or_app_user u on fp.userid = u.id')
			.where({'fp.orderid':orderid})
			.select();
			return this.json(fenpeiinfo);
		}
	}

	async tuidanlistAction () {
		let searchinfo = JSON.parse(this.post('searchinfo'));

		let where = {
			'o.departmentid': this.shop_userinfo.departmentid
		}

		if (searchinfo.times && (searchinfo.times[0] != null && searchinfo.times[1] != null)) {
			let begintime = Math.floor(new Date(searchinfo.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(searchinfo.times[1]).setHours(0,0,0,0)/1000) + 86400 // 当天加上一天
			where['o.addtime'] = {'>=': begintime, '<': endtime}
		}  


		if (searchinfo.ordertype != 0) where['o.ordertype'] = searchinfo.ordertype
		where['o.status'] = searchinfo.status == 0 ? ['!=', 0] : searchinfo.status
		if (searchinfo.search) where['g.name'] = ['like', '%' + searchinfo.search + '%']

		let list = await this.model('or_shop_backcardorder')
		.alias('o')
		.field('o.*, g.name, g.id as gid')
		.join('`think_or_guest` g on g.id=o.guestid')
		.where(where)
		.page(searchinfo.currentPage, searchinfo.pageSize)
		.order('o.addtime desc')
		.countSelect()

		return this.json(list);
	}

}